//购物车小仓库
import { getCardList, delCarGoods, updateGoodsChecked } from '@/api'

const state = {
  cardList: [],
}
const actions = {
  async getCardList(context) {
    let result = await getCardList()
    if (result.code == 200) {
      context.commit('GETCARDLIST', result.data)
    }
  },
  async delCarGoods(context, skuId) {
    let result = await delCarGoods(skuId)
    if (result.code == 200) {
      return 'OK'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  async updateGoodsChecked(context, { skuId, isChecked }) {
    let result = await updateGoodsChecked(skuId, isChecked)
    if (result.code == '200') {
      return 'OK'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  delAllCheckedGoods({ dispatch, getters }) {
    let PromiseAll = []
    getters.cartInfoList.forEach((good) => {
      if (good.isChecked) {
        let promise = dispatch('delCarGoods', good.skuId)
        PromiseAll.push(promise)
      }
    })
    return Promise.all(PromiseAll)
  },
  changAllchecked({ dispatch, getters }, status) {
    let promiseAll = []
    getters.cartInfoList.forEach((element) => {
      let result = dispatch('updateGoodsChecked', {
        skuId: element.skuId,
        isChecked: status,
      })
      promiseAll.push(result)
    })
    return Promise.all(promiseAll)
  },
}
const mutations = {
  GETCARDLIST(state, value) {
    state.cardList = value
  },
}
const getters = {
  cartInfoList(state) {
    if (!state.cardList) {
      return []
    } else if (!state.cardList[0]) {
      return []
    } else if (state.cardList[0]) {
      return state.cardList[0].cartInfoList
    }
  },
}

export default {
  namespaced: 'shopCard',
  state,
  actions,
  mutations,
  getters,
}
